/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.listener;

import cn.easyplatform.lang.stream.StringWriter;
import cn.easyplatform.spi.listener.event.ConsoleEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Html;

import java.io.PrintWriter;
import java.util.Collection;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class MessageEventListener implements EventListener<Event> {

    private Html console;

    private StringBuilder sb = new StringBuilder();

    public MessageEventListener(Html console) {
        this.console = console;
        this.console.setContent("");
        if (this.console.getWidgetOverride("setContent") == null)
            this.console.setWidgetOverride("setContent", "function(v){var n=this.$n();if(n){if(v==='$$clear$$'||n.innerHTML.length>102400){n.innerHTML=''}else{n.innerHTML=n.innerHTML+v||'';jq(this.parent)[0].scrollTop=jq(this.parent)[0].scrollHeight}}}");
    }

    @Override
    public void onEvent(Event event) {
        Object msg = event.getData();
        if (msg instanceof ConsoleEvent) {
            ConsoleEvent evt = (ConsoleEvent) msg;
            if (evt.getData() instanceof String) {
                sb.append("<span  class=\"z-a\">");
                sb.append(" ");
                sb.append(evt.getTaskId());
                sb.append(" [");
                sb.append(evt.getName());
                sb.append("] ");
                sb.append("</span>");
                sb.append("<span class=\"z-label\">");
                String str = (String) evt.getData();
                if (str.startsWith("script:")) {
                    String[] items = str.substring(7).split("\\\n");
                    if (items.length > 0)
                        sb.append("</br>===========================================================================================</br>");
                    for (int i = 0; i < items.length; i++) {
                        sb.append(i + 1).append(" ").append(items[i]);
                        sb.append("</br>");
                    }
                    if (items.length > 0)
                        sb.append("===========================================================================================");
                } else
                    sb.append(str);
                sb.append("</span>");
                sb.append("</br>");
            } else if (evt.getData() instanceof Collection<?>) {//栏位或变量
                sb.append("<span  class=\"z-label\">");
                for (Object obj : (Collection<?>) evt.getData())
                    sb.append(obj).append("</br>");
                sb.append("</span>");
            } else if (evt.getData() instanceof Throwable) {//异常
                sb.append("<font size=\"1.5\" color=\"red\">");
                sb.append(" ");
                sb.append(evt.getTaskId());
                sb.append("</font>");
                sb.append(" [");
                sb.append(evt.getName());
                sb.append("] ");
                sb.append("<font size=\"1.5\" color=\"red\">");
                StringBuilder tmp = new StringBuilder();
                StringWriter w = new StringWriter(tmp);
                PrintWriter pw = new PrintWriter(w, true);
                ((Throwable) evt.getData()).printStackTrace(pw);
                String[] items = tmp.toString().split("\\\n");
                for (int i = 0; i < items.length; i++) {
                    sb.append(i + 1).append(" ").append(items[i]);
                    sb.append("</br>");
                }
                w = null;
                pw = null;
                sb.append("</font>");
                sb.append("</br>");
            } else {
                sb.append("<font size=\"1.5\" color=\"red\">");
                sb.append(" ");
                sb.append(evt.getTaskId());
                sb.append("</font>");
                sb.append(" [");
                sb.append(evt.getName());
                sb.append("] ");
                sb.append("<span class=\"z-label\">");
                sb.append(evt.getData());
                sb.append("</span>");
                sb.append("</br>");
            }
        } else
            sb.append(msg);
        console.setContent(sb.toString());
        sb.setLength(0);
    }

}
